import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { i18nChangeLanguage } from '@wangeditor/editor';
import { DomEditor } from '@wangeditor/editor'
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

const MyEditor = () => {
  const url = window.location.href;
  const searchParams = new URL(url).searchParams;
  const index = searchParams.get('index') || '0';
  const [editor, seteditor] = useState(null); // 存储 editor 实例
  const htmlRef = useRef({});
  const [htmlsta, setHtmlsta] = useState({});
  const textRef = useRef({});
  i18nChangeLanguage('en');
  const cookieObj = useMemo(() => {
    const allcookies = document.cookie || '';
    const obj = {};
    const cookiearray = allcookies.split('; ');
    for (var i = 0; i < cookiearray.length; i++) {
      let name = cookiearray[i].split('=')[0];
      let value = cookiearray[i].split('=')[1];
      obj[name] = value;
    }
    return obj;
  }, []);
  const i18HK = useMemo(() => cookieObj['i18n-1261'] === 'zh-HK', [cookieObj]);
  // 向iframe父页面发送消息
  function sendMsgToParent(e) {
    window.parent.postMessage(
      { action: 'get', html: htmlRef.current[index], text: textRef.current[index], index: index },
      '*'
    );
  }
  // 监听消息
  if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('message', dealMessage, false);
  } else if (typeof window.attachEvent != 'undefined') {
    window.attachEvent('onmessage', dealMessage);
  }
  function dealMessage(e) {
    if (e.data?.action === `value${index}`) {
      if (e.data?.data !== htmlRef.current[index]) {
        htmlRef.current[index] = e.data?.data;
        setHtmlsta(i => ({ ...i, [index]: e.data?.data }));
      }
    }
  }

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      seteditor(null);
    };
  }, [editor]);
  const deepfn = (el, fontSize) => {
    if (!el.childNodes || el.childNodes.length === 0) {
      return; // 如果没有子节点，直接返回
    }
    for (let i = 0; i < el.childNodes.length; i++) {
      const childNode = el.childNodes[i];
      if (childNode.nodeType === 1) {
        if (childNode.style.fontSize) {
          deepfn(childNode, childNode.style.fontSize);
        } else {
          if (fontSize) {
            childNode.style.fontSize = fontSize;
          }
          deepfn(childNode, fontSize);
        }
      }
    }
  };
  const editorConfig = useMemo(()=>( {
    placeholder: i18HK ? '請輸入10個字符以上的長度' : '请输入10个字符以上的长度',
    onBlur: e => {
      sendMsgToParent(e);
    }
  }),[ i18HK])
  const handleHtml = e => {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = e.getHtml();
    deepfn(tempDiv);
    return tempDiv.innerHTML;
  };
  const debouncedOnSearch = debounce(e => {
    sendMsgToParent(e);
  }, 1000);
  const handleChang = e => {
    if (e.getText()) {
      const newhtml = handleHtml(e);
      htmlRef.current[index] = newhtml;
      textRef.current[index] = e.getText();
      debouncedOnSearch(e);
    }
  };
  const toolbarConfig = {
    excludeKeys: [
      'emotion',
      'insertLink',
      'todo',
      'group-indent',
      'group-image',
      'group-video',
      'insertTable',
      'codeBlock',
      "fullScreen"
    ]
  };
  // useEffect(() => {
    
  //   const toolbar = DomEditor.getToolbar(editor)

  // console.log(toolbar ) 
  //   return () => {
      
  //   }
  // }, [editor])
  


  return (
    <div
      style={{
        height: '100%',
        width: '100%',
        border: '1px solid #ccc',
        boxSizing: 'border-box'
      }}
    >
      <div style={{ zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={htmlsta[index]}
          onCreated={seteditor}
          onChange={e => {
            handleChang(e);
          }}
          mode="default"
          style={{ height: '300px' }}
        />
      </div>
    </div>
  );
};

export default MyEditor;
